package com.zscat.mallplus.utils;

import cn.hutool.extra.mail.Mail;
import cn.hutool.extra.mail.MailAccount;
import com.google.common.collect.Lists;
import com.sun.mail.smtp.SMTPTransport;
import com.zscat.mallplus.exception.BusinessMallException;
import com.zscat.mallplus.sys.entity.SysEmailConfig;
import com.zscat.mallplus.sys.vo.EmailVo;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import java.io.File;
import java.util.Properties;

/**
 * @author Created by 谭健 on 2020/9/19. 星期六. 14:21.
 * © All Rights Reserved.
 */
public class EmailUtils {




    public static void  sendEmail(EmailVo emailVo){
        // 示例
//        EmailVo emailVo = new EmailVo();
//        emailVo.setContent("周五有空吗，出来玩  *  周五有空吗，出来玩 **  周五有空吗，出来玩");
//        emailVo.setSubject("周五有空吗，出来玩");
//        emailVo.setTos(Lists.newArrayList("347969164@qq.com"));

        SysEmailConfig emailConfig = new SysEmailConfig();
        emailConfig.setHost("smtp.163.com");
        emailConfig.setFromUser("yingweihu123@163.com");
        emailConfig.setPass("EQHCOPFQUWXXYXAJ");
        emailConfig.setUser("yingweihu123@163.com");
        emailConfig.setPort("465");


        if (emailConfig == null) {
            throw new BusinessMallException("请先配置，再操作");
        }
        // 封装
        MailAccount account = new MailAccount();
        account.setHost(emailConfig.getHost());
        account.setPort(Integer.parseInt(emailConfig.getPort()));
        account.setAuth(true);
        try {
            // 对称解密
//            account.setPass(EncryptUtils.desDecrypt(emailConfig.getPass()));
            account.setPass(emailConfig.getPass());
        } catch (Exception e) {
            throw new BusinessMallException(e.getMessage());
        }
        account.setFrom(emailConfig.getUser() + "<" + emailConfig.getFromUser() + ">");
        // ssl方式发送
        account.setSslEnable(true);
        String content = emailVo.getContent();
        // 发送
        try {
            int size = emailVo.getTos().size();
            Mail.create(account)
                    .setTos(emailVo.getTos().toArray(new String[size]))
                    .setTitle(emailVo.getSubject())
                    .setContent(content)
                    .setHtml(true)
                    //关闭session
                    .setUseGlobalSession(false)
                    .send();
        } catch (Exception e) {
            throw new BusinessMallException(e.getMessage());
        }
    }









    private static final String SENDCLOUD_SMTP_HOST = "smtp.sendcloud.net";
    private static final int SENDCLOUD_SMTP_PORT = 25;

    private static String getMessage(String reply) {
        String[] arr = reply.split("#");

        String messageId = null;

        if (arr[0].equalsIgnoreCase("250 ")) {
            messageId = arr[1];
        }

        return messageId;
    }



    public static void main(String[] args) throws Exception{

        // configure javamail
        Properties props = System.getProperties();
        props.setProperty("mail.transport.protocol", "smtp");
        props.put("mail.smtp.host", SENDCLOUD_SMTP_HOST);
        props.put("mail.smtp.port", SENDCLOUD_SMTP_PORT);
        props.setProperty("mail.smtp.auth", "true");
        props.put("mail.smtp.connectiontimeout", 180);
        props.put("mail.smtp.timeout", 600);
        props.setProperty("mail.mime.encodefilename", "true");

        // Verification using api_user and api_key
        final String apiUser = "yingweihu_test_7HFbR7";
        final String apiKey = "rPEWltAsXoHeK8Zj";

        String to = "347969164@qq.com";

        Session mailSession = Session.getInstance(props, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(apiUser, apiKey);
            }
        });

        SMTPTransport transport = (SMTPTransport) mailSession.getTransport("smtp");

        MimeMessage message = new MimeMessage(mailSession);
        // The from, use the correct email address instead
        message.setFrom(new InternetAddress("Rgmaexcd3rYqqpc1LPhjStzH6hGcluUQ.sendcloud.org\t", "fromname", "UTF-8"));
        // The recipient address,use the correct email address instead
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
        // Mail theme
        message.setSubject("SendCloud java smtp example", "UTF-8");

        Multipart multipart = new MimeMultipart("alternative");

        // Add HTML message body
        String html = "<html><head></head><body>" + "<p>Welcome to<a href='http://sendcloud.sohu.com'>SendCloud!</a></p>" + "</body></html> ";
        BodyPart contentPart = new MimeBodyPart();
        contentPart.setHeader("Content-Type", "text/html;charset=UTF-8");
        contentPart.setHeader("Content-Transfer-Encoding", "base64");
        contentPart.setContent(html, "text/html;charset=UTF-8");
        multipart.addBodyPart(contentPart);

        // Add attachment ( SMTP cannot use FileStream )
        File file = new File("/path/file");
        BodyPart attachmentBodyPart = new MimeBodyPart();
        DataSource source = new FileDataSource(file);
        attachmentBodyPart.setDataHandler(new DataHandler(source));
        attachmentBodyPart.setFileName(MimeUtility.encodeWord(file.getName()));
        multipart.addBodyPart(attachmentBodyPart);
        message.setContent(multipart);

        // Connect to sendcloud server and send mail
        transport.connect();
        transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO));

        String messageId = getMessage(transport.getLastServerResponse());
        String emailId = messageId + "0$" + to;
        System.out.println("messageId:" + messageId);
        System.out.println("emailId:" + emailId);
        transport.close();
    }
}
